﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Text;
using ChgDoc.Extension;

namespace ChgDoc.Service
{
    /// <summary>
    /// Summary description for MyService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class Files : System.Web.Services.WebService
    {
        [WebMethod]
        public string DirectoryList(string from)
        {
            if (from.StartsWith("/"))
                from = from.Substring(1);

            // ** Security ** Make sure you us GetFullPath to stop hacker browsing outside of UploadFolder with ../../ etc
            string fromPath = Path.GetFullPath(Path.Combine(Config.UploadFolder, from));
            if (!fromPath.StartsWith(Config.UploadFolder))
                return "{}";

            StringBuilder json = new StringBuilder();
            json.Append("{ \"path\" : \"" + from + "\", \"rootUrl\" : \"" + Config.UploadFolderUrl +"\", \"content\": [");

            json.Join(", ",
                    (from dir
                        in Directory.GetDirectories(fromPath)
                     select
                         string.Format("{{ \"type\": \"directory\", \"value\" : \"{0}\", \"thumb\": \"folder.jpg\" }}",
                         dir.Split('\\').Last()))
                    .Union(
                      from filename
                        in Directory.GetFiles(fromPath)
                      select
                        string.Format("{{ \"type\" : \"file\", \"value\": \"{0}\", \"thumb\": \"folder.jpg\"  }}",
                        Path.GetFileName(filename))));
            json.Append("]}");

            return json.ToString();
        }

    }
}